import { getMockUserInfo, getUserInfo, isProduction, getToken } from '@/js/utils/browser.js'
import Axios from 'axios'
import { zipSync, unzipSync, strToU8, strFromU8 } from 'fflate'

import Qs from 'qs'
const getApi = (api = '') => {
  return api || process.env.NODE_ENV === 'production' ? '' : ''
}
const axios = Axios.create({
  baseURL: getApi(),
  withCredentials: true,
  timeout: 120000, // 超时 20s
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Cache-Control': 'no-cache'
  }
})
axios.defaults.paramsSerializer = (params) => {
  return Qs.stringify(params, { arrayFormat: 'brackets' })
}
/**
 * 获取响应中指定响应头的值
 * @param XhrResponse response
 * @param key 响应头的key
 * @returns {*|string}
 */
const getXhrResponseHeader = function (XhrResponse, key) {
  let value

  if (XhrResponse.getResponseHeader) {
    value = XhrResponse.getResponseHeader(key)
  } else if (XhrResponse.headers && XhrResponse.headers[key.toLowerCase()]) {
    // key值在headers里会被转为小写
    value = XhrResponse.headers[key.toLowerCase()]
  }
  return value
}

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (config.baseURL === undefined) {
      config.baseURL = getApi()
    }
    if (config.timeout <= 0) {
      config.timeout = 120000
    }
    const { Cookie, Authorization } = isProduction() ? getUserInfo() : getMockUserInfo()
    // config.headers['token'] = token;
    config.headers['Authorization'] = Authorization
    config.headers['X-Auth-Token'] = getToken() || window.localStorage.getItem('token')
    // config.headers['uid'] = uid;
    // config.headers['productid'] = productInfo?.id;
    // config.headers['tenantid'] = productInfo?.tenantId;
    // config.headers['appId'] = appId;
    // config.headers['current_tenant_id'] = '1';
    return config
  },
  (error) => {
    Promise.reject(error).then((r) => console.log(r))
  }
)

/**
 * 缓存请求，同一请求的拦截不再向后台发送
 * @param config
 */
const ajax = (config) => {
  return axios(config).then(
    (response) => {
      const result = response.data
      const errorMsg = getXhrResponseHeader(response, 'errorMsg')
      if (errorMsg) {
        result.errorMsg = errorMsg
      }
      return result
    },
    (err) => {
      console.error(err)
      return null
    }
  )
}

export const get = (url, data = {}, config = {}) => {
  config = config || {}
  if (!config.baseURL) config.baseURL = getApi()
  config.method = 'get'
  config.url = url
  config.params = data
  return ajax(config)
}

export const getJsonFile = (url, data = {}, config = {}) => {
  config = config || {}
  if (!config.baseURL) config.baseURL = getApi()
  config.method = 'get'
  config.url = url
  ;(config.responseType = 'blob'), (config.params = data)
  config.onDownloadProgress = function (progressEvent) {
    let persent = progressEvent.loaded / progressEvent.total || 0
    config.fun && config.fun(persent)
  }
  return ajax(config)
}

export const getByData = (url, data = {}, config = {}) => {
  config = config || {}
  if (!config.baseURL) config.baseURL = getApi()
  config.method = 'get'
  config.url = url
  config.data = data
  return ajax(config)
}

export const post = (url, data = {}, config = {}) => {
  config = config || {}
  if (!config.baseURL) config.baseURL = getApi()
  config.method = 'post'
  config.url = url
  config.data = data
  return ajax(config)
}

export const _handleFflateUnzip = async (file, resolve) => {
  let reader = new FileReader()
  reader.addEventListener('load', (e) => {
    let zip = unzipSync(new Uint8Array(e.target.result))
    let data = strFromU8(zip['scene.json'])
    resolve(JSON.parse(data))
  })

  reader.readAsArrayBuffer(file)
}

export const _handleBlob = async (file, resolve) => {
  let reader = new FileReader()
  reader.onload = function (e) {
    let data = JSON.parse(e.target.result)
    resolve(data)
  }
  reader.readAsText(file)
}
